/**
 * 
 */
package com.activities;


import java.io.File;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.Adapters.ProfileAdapter;
import com.Adapters.Items.ItemProfile;
import com.Animations.AnimUtil;
import com.Animations.AnimUtil.AnimationCompleted;
import com.Data.Albums;
import com.Data.Albums.onDeleteCompleted;
import com.Data.Albums.onGetCompleted;
import com.Data.Albums.onUpdateCompleted;
import com.Data.User;
import com.Dialogs.DialogCover_Album;
import com.Dialogs.DialogOneText;
import com.Dialogs.DialogOneText.OnClickOkListener;
import com.Dialogs.DialogShare;
import com.Dialogs.DialogShare.OnShareChanged;
import com.Downloaders.ProfilePictureDownloader;
import com.Downloaders.ProfilePictureDownloader.onProfilePictureDownloaded;
import com.Downloaders.ThumbDownloader;
import com.Downloaders.ThumbDownloader.ThumbnailPathCompleted;
import com.Enums.BlurType;
import com.Managers.DirManagerClass;
import com.Managers.FragmentManagerClass;
import com.Managers.PictureManagerClass.CreateBlurAsync;
import com.Managers.PictureManagerClass.OnBlurCompleted;
import com.Managers.ThemeManager;
import com.Managers.UserManagerClass;
import com.TextFormat.UtilFonts;
import com.UtilDate.UtilDate;
import com.shareup.R;


/**
 * @author Chris
 * 
 */
public class ActivityAlbumInfo extends Activity {

    private static final int ITEM_DELETE = 22;

    private static final int ITEM_PIN = 20;

    private static final int ITEM_PRIVACY = 21;

    private boolean isDeleting;

    static Albums album;

    private TextView albumName;

    private final OnClickListener backClick = new OnClickListener() {

        @Override
        public void onClick(View v) {

            exit();

        }
    };

    private ImageView mCover;

    private final OnClickListener coverClick = new OnClickListener() {

        @Override
        public void onClick(View v) {

            showDialogCover();
        }
    };

    private ImageView editCover;

    private TextView header;

    private int ITEM_DATE;

    private ListView list;

    private ProfileAdapter adapter;

    private final OnItemClickListener listClick = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {

            position = Integer.parseInt(v.getTag().toString());
            switch (position) {
                case ITEM_PIN:
                    showDialogEditPin(String.valueOf(album.getPin()));
                    break;
                case ITEM_PRIVACY:
                    showDialogEditPrivacy();
                    break;
                case ITEM_DELETE:
                    showDialogDelete();
                    break;
                default:

                    break;
            }

        }

    };

    private ImageView mProfile;

    private final OnLongClickListener nameClick = new OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {

            TextView tV = (TextView) v;
            String text = (String) tV.getText();
            showDialogEditName(text);

            return false;
        }
    };

    private TextView nombre;

    private TextView pictures;

    private TextView picturesCounter;

    private ProgressBar progress;

    private ProgressBar progressCover;

    private RelativeLayout socialInfo;

    boolean hasChanged = false;

    public void changeCoverAlbum() {

    }

    public void deleteCoverAlbum() {

        if (!album.getCover().equals("0")) {
            Albums als = new Albums(Albums.ACTION_UPDATE_COVER);
            als.setContext(this);
            als.setID(album.getID());
            als.setCover("0");

            als.setCallbackUpdate(new onUpdateCompleted() {

                @Override
                public void Completed(String result) {

                    AnimUtil.AnimateDrawablesOutImage(mCover);
                    album.setCover("0");
                    hasChanged = true;

                }
            });
            als.execute();
        }

    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            //
            return true;
        }
        //
        return super.onKeyUp(keyCode, event);
    }

    private void addToList() {

        AnimUtil.animateFadeOut(list, new AnimationCompleted() {

            @Override
            public void Completed() {

                addItems();

            }
        });

    }

    private void addItems() {

        adapter = new ProfileAdapter(this);
        adapter.clear();
        list.setAdapter(null);

        String pin = getResources().getString(R.string.album_pin);
        if (album.getPin() != 0)
            pin += album.getPin();
        else
            pin += " "
                        + getResources().getString(R.string.album_pincode_no_pin);
        //
        String[] shared = getResources().getStringArray(R.array.picture_shared_with);
        String shr = getResources().getString(R.string.album_shared_with)
                    + " " + shared[album.getPrivacy()];
        String date = getResources().getString(R.string.album_creation_date)
                    + " "
                    + new UtilDate(this).convertDatetoCurrentZone(album.getDate()).split(" ")[0];

        int albumid = album.getOwner().getID();
        int myid = UserManagerClass.UserLogged.getID();
        if (albumid == myid)
            adapter.add(new ItemProfile(pin, R.drawable.pin_light, ITEM_PIN, false));

        adapter.add(new ItemProfile(date, R.drawable.date_light, ITEM_DATE, false));
        adapter.add(new ItemProfile(shr, R.drawable.shared_light, ITEM_PRIVACY, false));

        if (albumid == myid)
            adapter.add(new ItemProfile(getResources().getString(R.string.string_delete), R.drawable.delete_normal_light, ITEM_DELETE, false));

        list.setAdapter(adapter);
        AnimUtil.animateFadeIn(list);
        list.setOnItemClickListener(listClick);
    }

    private void delayTask(final Albums album) {

        Handler myHandler = new Handler();
        myHandler.postDelayed(new Runnable() {

            @Override
            public void run() {

                album.execute();
            }
            //
        }, 1000);
    }

    private void downloadCover(String path) {

        if (path != null && !path.equals("null") && !path.equals("0")) {

            path = path.replace("cache/", "");

            String ps = DirManagerClass.getSDPath()
                        + DirManagerClass.ThumbsPath;
            ps += DirManagerClass.getPictureNameWE(path);

            Log.e("ps", ps);

            if (new File(ps).exists())
                createBlur(ps);
            else {
                Log.e("ps", "downloaded");
                ThumbDownloader td = new ThumbDownloader(this, path);
                td.setCompletePath(new ThumbnailPathCompleted() {

                    @Override
                    public void Completed(String path) {

                        createBlur(path);

                    }
                });
                td.execute();
            }

        }
        else
            AnimUtil.AnimateFadeOutIn(editCover, true, null, progressCover);

    }

    private void createBlur(String path) {

        int Blur = BlurType.BLUR_COVER.getValue();
        CreateBlurAsync cbs = new CreateBlurAsync(Blur, mCover, path, new OnBlurCompleted() {

            @Override
            public void Completed() {

                AnimUtil.AnimateFadeOutIn(editCover, true, null, progressCover);

            }
        });

        cbs.setUserProfile(true);
        cbs.execute();
    }

    private void downloadProfilePicture(final ImageView profile) {

        progress.setVisibility(View.VISIBLE);
        ProfilePictureDownloader pd = new ProfilePictureDownloader();
        pd.setProgress(progress);
        pd.setCallbackProfilePicture(new onProfilePictureDownloaded() {

            @Override
            public void completed(Bitmap result) {

                AnimUtil.animatePictureChanges(mProfile, result);
                downloadCover(album.getCover());

            }
        });
        pd.execute(album.getOwner().getProfilePicture());

    }

    private void delete() {

        FragmentManagerClass.aAlbum.remove(album, new onDeleteCompleted() {

            @Override
            public void Completed(String result) {

                hasChanged = false;
                isDeleting = false;
                FragmentManagerClass.aAlbum.remove(album);

                FragmentManagerClass.aAlbumDetail.finish();

                exit();

            }
        });
    }

    private void exit() {

        if (hasChanged)
            updateAlbum();
        else {

            finish();
            AnimUtil.getActivityTransition(this, false);
        }

    }

    private void getAlbumInfo() {

        Albums al = new Albums(Albums.ACTION_GET);
        al.setSingleAlbum(true);
        al.setCallbackGet(new onGetCompleted() {

            @Override
            public void Completed(Albums[] result) {

                if (result.length > 0)
                    album = result[0];

                setTextInfo();

            }
        });
        User us = new User();
        us.setID(album.getID());
        al.setOwner(us);

        this.delayTask(al);
    }

    private void init() {

        ImageView backB = (ImageView) findViewById(R.id.button_back);
        header = (TextView) findViewById(R.id.aprofile_header);
        UtilFonts.setTextBoldFont(header);
        backB.setOnClickListener(backClick);
        //
        mCover = (ImageView) this.findViewById(R.id.coverView);
        mProfile = (ImageView) this.findViewById(R.id.aprofile_image);

        list = (ListView) this.findViewById(R.id.list_profile_edit);
        list.setVisibility(View.INVISIBLE);
        //
        progress = (ProgressBar) findViewById(R.id.loading_progress);
        progressCover = (ProgressBar) findViewById(R.id.loading_cover);
        //
        editCover = (ImageView) this.findViewById(R.id.menu_edit_cover);
        editCover.setOnClickListener(coverClick);
        editCover.setVisibility(View.GONE);
        nombre = (TextView) this.findViewById(R.id.user_name);
        albumName = (TextView) this.findViewById(R.id.name);
        UtilFonts.setTextBoldFont(nombre);
        UtilFonts.setTextBoldFont(albumName);
        // SETTING THE NAME OF THE OWNER OF THE ALBUM
        String owner = getResources().getString(R.string.album_owner);
        nombre.setText(String.format(owner, album.getOwner().getRealName()));
        //
        albumName.setText(album.getName());
        socialInfo = (RelativeLayout) findViewById(R.id.table_info);
        socialInfo.setVisibility(View.INVISIBLE);
        pictures = (TextView) this.findViewById(R.id.aprofile_pictures);
        picturesCounter = (TextView) this.findViewById(R.id.profile_p_counter);
        UtilFonts.setTextRegularFont(pictures, picturesCounter);
        //
        albumName.setOnLongClickListener(nameClick);

        downloadProfilePicture(mProfile);
        //
        getAlbumInfo();

    }

    private void setTextInfo() {

        picturesCounter.setText(String.valueOf(album.getCount()));
        AnimUtil.animateFadeIn(socialInfo);

        addToList();

    }

    private void showDialogCover() {

        DialogCover_Album da = new DialogCover_Album(this);
        da.setAlbumActivity(this);
        da.show();
    }

    private void showDialogDelete() {

        AlertDialog.Builder dg = new AlertDialog.Builder(this);
        View v = LayoutInflater.from(this).inflate(R.layout.dialog_actions, null);
        TextView message = (TextView) v.findViewById(R.id.message_dialog);
        UtilFonts.setTextRegularFont(message);
        Button accept = (Button) v.findViewById(R.id.dialog_action_a_button);
        UtilFonts.setTextRegularFont(accept);
        Button cancel = (Button) v.findViewById(R.id.dialog_action_c_button);
        UtilFonts.setTextRegularFont(cancel);
        //
        message.setText(R.string.dialog_question_delete_album_message);
        //
        dg.setView(v);
        //
        final AlertDialog alert = dg.create();
        accept.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                isDeleting = true;

                alert.dismiss();
            }
        });
        cancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                alert.dismiss();
            }
        });
        //
        //
        //
        alert.setOnDismissListener(new OnDismissListener() {

            @Override
            public void onDismiss(DialogInterface dialog) {

                if (isDeleting)
                    delete();

            }

        });
        alert.show();

    }

    private void showDialogEditName(final String text) {

        DialogOneText ded = new DialogOneText(this, new OnClickOkListener() {

            @Override
            public void OnClick(String text) {

                if (!album.getName().equals(text)) {
                    hasChanged = true;
                    album.setName(text);
                    albumName.setText(text);
                }

            }
        });
        ded.setHint(getResources().getString(R.string.crop_new_album_name));
        ded.setText(text);
        ded.setMinLength(3);
        ded.setMaxLength(50);
        ded.show();
    }

    private void showDialogEditPrivacy() {

        DialogShare sha = new DialogShare(this, new OnShareChanged() {

            @Override
            public void Changed(int share) {

                if (album.getPrivacy() != share) {
                    album.setPrivacy(share);
                    hasChanged = true;
                    addToList();
                }

            }
        });
        sha.show();

    }

    private void showDialogEditPin(String pin) {

        DialogOneText ded = new DialogOneText(this, new OnClickOkListener() {

            @Override
            public void OnClick(String text) {

                int pin = Integer.parseInt(text);
                if (album.getPin() != pin) {
                    hasChanged = true;
                    album.setPin(pin);
                    addToList();
                }

            }
        });

        ded.setText(pin);
        ded.setType(InputType.TYPE_CLASS_NUMBER);
        ded.setHint(getResources().getString(R.string.crop_new_pin));
        ded.setMinLength(4);
        ded.setMaxLength(4);
        ded.show();
    }

    /**
     * 
     */
    private void updateAlbum() {

        Albums send = new Albums(Albums.ACTION_UPDATE);
        send.setContext(this);
        send.setCallbackUpdate(new onUpdateCompleted() {

            @Override
            public void Completed(String result) {

                hasChanged = false;
                updateAlbum(album);
                exit();

            }
        });

        send.setID(album.getID());
        send.setOwner(album.getOwner());
        send.setPin(album.getPin());
        send.setPrivacy(album.getPrivacy());
        send.setName(album.getName());
        send.setCover(album.getCover());

        send.execute();

    }

    private void updateAlbum(Albums album) {

        FragmentManagerClass.aAlbum.setAlbum(album);
        addToList();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        ThemeManager.setTheme(this);
        setContentView(R.layout.activity_album_edit);
        super.onCreate(savedInstanceState);

        init();
    }

    @Override
    protected void onDestroy() {

        album = null;
        super.onDestroy();
    }

}
